<?php
namespace app\controllers;
use Yii;
use yii\db\Query;
use yii\helpers\Url;

class RoutingController extends BaseController
{
    /**
     * 呼出路由列表
     * @return string|\yii\web\Response
     */
    public function actionIndex()
    {
        if (Yii::$app->request->isAjax){
            $db = (new Query())->from('outbound_routes');
            $count = $db->count('route_id',$this->asterisk_db);
            $page = Yii::$app->request->get('page',1);
            $limit = Yii::$app->request->get('limit',10);
            $data = $db->offset(($page-1)*$limit)->limit($limit)->all($this->asterisk_db);
            foreach ($data as &$d){
                $d['edit_url'] = Url::to(['edit','route_id'=>$d['route_id']]);
                $d['destroy_url'] = Url::to(['destroy','route_id'=>$d['route_id']]);
            }
            return $this->asJson([
                'code' => 0,
                'msg' => '请求成功',
                'count' => $count,
                'data' => $data
            ]);
        }
        return $this->render('index');
    }

    /**
     * 添加出局路由
     * @return string|\yii\web\Response
     */
    public function actionCreate()
    {
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            //获取route_id
            $route_id = (new Query())->from('outbound_routes')->max('route_id',$this->asterisk_db);
            $route_id++;
            $maxSeq = (new Query())->from('outbound_route_sequence')->max('seq',$this->asterisk_db);
            $maxSeq++;
            $transaction = $this->asterisk_db->beginTransaction();
            try{
                //写入outbound_routes表
                $this->asterisk_db->createCommand()->insert('outbound_routes',[
                    'route_id'      => $route_id,
                    'name'          => $data['name'],
                    'outcid'        => $data['outcid'],
                    'outcid_mode'   => $data['outcid_mode'],
                    'mohclass'      => 'default'

                ])->execute();
                //写入outbound_route_trunks表
                foreach (array_filter($data['trunkid']) as $k=>$v){
                    $this->asterisk_db->createCommand()->insert('outbound_route_trunks',[
                        'route_id'  => $route_id,
                        'trunk_id'  => $v,
                        'seq'       => $k
                    ])->execute();
                }
                //写入outbound_route_sequence表
                $this->asterisk_db->createCommand()->insert('outbound_route_sequence',[
                    'route_id'  => $route_id,
                    'seq'       => empty($data['seq'])?$maxSeq:$data['seq']
                ])->execute();
                //写入outbound_route_patterns表
                if (!empty($data['dialpatterns'])){
                    foreach ($data['dialpatterns'] as $d){
                        $this->asterisk_db->createCommand()->insert('outbound_route_patterns',[
                            'route_id'              => $route_id,
                            'match_pattern_prefix'  => $d['match_pattern_prefix'],
                            'match_pattern_pass'    => $d['match_pattern_pass'],
                            'match_cid'             => $d['match_cid'],
                            'prepend_digits'        => $d['prepend_digits'],
                        ])->execute();
                    }
                }
                $transaction->commit();
                $this->reload();
                return $this->asJson(['code'=>0,'msg'=>'添加成功']);
            }catch (\Exception $exception){
                $transaction->rollBack();
                return $this->asJson(['code'=>1,'msg'=>'添加失败','data'=>$exception->getMessage()]);
            }
        }
        $trunks = (new Query())->from('trunks')->orderBy('trunkid asc')->all($this->asterisk_db);
        return $this->render('create',['trunks'=>$trunks]);
    }

    /**
     * 编辑呼出路由
     * @return string|\yii\web\Response
     *
     */
    public function actionEdit()
    {
        $route_id = Yii::$app->request->get('route_id');
        $trunks = (new Query())->from('trunks')->orderBy('trunkid asc')->all($this->asterisk_db);
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $transaction = $this->asterisk_db->beginTransaction();
            try{
                //更新outbound_routes表
                $this->asterisk_db->createCommand()->update('outbound_routes',[
                    'name'          => $data['name'],
                    'outcid'        => $data['outcid'],
                    'outcid_mode'   => $data['outcid_mode'],
                    'mohclass'      => 'default'
                ],['route_id' => $route_id])->execute();
                //更新outbound_route_trunks表
                $this->asterisk_db->createCommand()->delete('outbound_route_trunks',['route_id' => $route_id])->execute();
                foreach (array_filter($data['trunkid']) as $k=>$v){
                    $this->asterisk_db->createCommand()->insert('outbound_route_trunks',[
                        'route_id'  => $route_id,
                        'trunk_id'  => $v,
                        'seq'       => $k
                    ])->execute();
                }
                //写入outbound_route_sequence表
                if (isset($data['seq'])){
                    $this->asterisk_db->createCommand()->update('outbound_route_sequence',[
                        'seq' => $data['seq']
                    ],['route_id' => $route_id])->execute();
                }
                //写入outbound_route_patterns表
                $this->asterisk_db->createCommand()->delete('outbound_route_patterns',['route_id' => $route_id])->execute();
                if (!empty($data['dialpatterns'])){
                    foreach ($data['dialpatterns'] as $d){
                        $this->asterisk_db->createCommand()->insert('outbound_route_patterns',[
                            'route_id'              => $route_id,
                            'match_pattern_prefix'  => $d['match_pattern_prefix'],
                            'match_pattern_pass'    => $d['match_pattern_pass'],
                            'match_cid'             => $d['match_cid'],
                            'prepend_digits'        => $d['prepend_digits'],
                        ])->execute();
                    }
                }
                $transaction->commit();
                $this->reload();
                return $this->asJson(['code'=>0,'msg'=>'更新成功']);
            }catch (\Exception $exception){
                $transaction->rollBack();
                return $this->asJson(['code'=>1,'msg'=>'更新失败','data'=>$exception->getMessage()]);
            }
        }
        $route = (new Query())->from('outbound_routes')->where(['route_id'=>$route_id])->one($this->asterisk_db);
        $sequence = (new Query())->from('outbound_route_sequence')->where(['route_id'=>$route_id])->one($this->asterisk_db);
        $seq = $sequence['seq'];
        $route_trunks = (new Query())->from('outbound_route_trunks')->where(['route_id'=>$route_id])->orderBy('seq asc')->all($this->asterisk_db);
        $patterns = (new Query())->from('outbound_route_patterns')->where(['route_id'=>$route_id])->all($this->asterisk_db);
        return $this->render('edit',['trunks'=>$trunks,'route'=>$route,'seq'=>$seq,'route_trunks'=>$route_trunks,'patterns'=>$patterns]);
    }

    /**
     * 删除出局路由
     * @return \yii\web\Response
     */
    public function actionDestroy()
    {
        $route_id = Yii::$app->request->post('route_id');
        $transaction = $this->asterisk_db->beginTransaction();
        try{
            //删除outbound_routes表
            $this->asterisk_db->createCommand()->delete('outbound_routes',['route_id'=>$route_id])->execute();
            //删除outbound_route_patterns表
            $this->asterisk_db->createCommand()->delete('outbound_route_patterns',['route_id'=>$route_id])->execute();
            //删除outbound_route_sequence表
            $this->asterisk_db->createCommand()->delete('outbound_route_sequence',['route_id'=>$route_id])->execute();
            //删除outbound_route_trunks表
            $this->asterisk_db->createCommand()->delete('outbound_route_trunks',['route_id'=>$route_id])->execute();
            $transaction->commit();
            $this->reload();
            return $this->asJson(['code'=>0,'msg'=>'删除成功']);
        }catch (\Exception $exception){
            $transaction->rollBack();
            return $this->asJson(['code'=>1,'msg'=>'删除失败','data'=>$exception->getMessage()]);
        }
    }

}